<!-- src/views/ArchiveManagementNew.vue -->
<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <PageHeader title="档案管理">
      <!-- 搜索和筛选区域 -->
      <template #search-filters>
        <!-- 档案搜索 -->
        <div class="archive-search">
          <span class="label">档案搜索：</span>
          <el-tooltip content="支持搜索档案名称、档案编号" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索档案名称、档案编号"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 日期范围选择 -->
        <div class="archive-date-range">
          <span class="label">档案日期：</span>
          <el-tooltip content="选择档案日期范围进行筛选" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 280px"
            @change="handleDateRangeChange"
          />
        </div>

        <!-- 年份筛选 -->
        <div class="archive-year-select">
          <span class="label">年份筛选：</span>
          <el-tooltip content="快速选择年份进行筛选" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-select
            v-model="selectedYear"
            placeholder="选择年份"
            clearable
            style="width: 120px"
            @change="handleYearChange"
          >
            <el-option label="全部年份" value="" />
            <el-option 
              v-for="year in yearOptions" 
              :key="year" 
              :label="`${year}年`" 
              :value="year" 
            />
          </el-select>
        </div>
      </template>

      <!-- 主要操作按钮 -->
      <template #main-actions>
        <el-button @click="handleAdd" type="primary" :disabled="!selectedCategory || !isLeafCategory(selectedCategory)">
          <el-icon><Plus /></el-icon>
          新建档案
        </el-button>
      </template>

      <!-- 更多操作下拉菜单 -->
      <template #more-actions>
        <el-dropdown @command="handleMoreAction">
          <el-button type="info">
            <el-icon><More /></el-icon>
            更多
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="reset" icon="Refresh">重置筛选</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </PageHeader>

    <!-- 数据表格 -->
    <div class="table-container">
      <div class="archive-layout">
        <!-- 左侧分类树 -->
        <div class="category-sidebar" :class="{ 'collapsed': sidebarCollapsed }">
          <div class="sidebar-header">
            <h3 v-show="!sidebarCollapsed">档案分类</h3>
            <div class="sidebar-controls">
              <el-button 
                type="text" 
                size="small" 
                @click="refreshCategories"
                :loading="categoryLoading"
                v-show="!sidebarCollapsed"
              >
                <el-icon><Refresh /></el-icon>
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="toggleSidebar"
                class="collapse-button"
              >
                <el-icon v-if="!sidebarCollapsed"><ArrowLeft /></el-icon>
                <el-icon v-else><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
          
          <div class="category-tree" v-show="!sidebarCollapsed">
            <el-tree
              ref="categoryTreeRef"
              :data="categoryTreeData"
              :props="categoryTreeProps"
              :expand-on-click-node="false"
              :highlight-current="true"
              node-key="id"
              @node-click="handleCategoryClick"
              @node-expand="handleCategoryExpand"
              @node-collapse="handleCategoryCollapse"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <div class="node-content">
                    <span class="node-name">{{ data.typeName }}</span>
                    <span class="node-count" v-if="data.archiveCount !== undefined">
                      ({{ data.archiveCount }})
                    </span>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>

        <!-- 右侧档案列表 -->
        <div class="archive-content">
          <div class="content-header">
            <div class="breadcrumb">
              <span v-if="selectedCategory">{{ selectedCategory.typeName }}</span>
              <span v-else>全部档案</span>
            </div>
            <div class="content-actions">
              <el-button type="primary" size="small" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新建档案
              </el-button>
            </div>
          </div>

          <!-- 档案表格 -->
          <div class="archive-table-container">
            <el-table
              :data="archiveList"
              v-loading="tableLoading"
              style="width: 100%"
              size="default"
              stripe
              border
              height="calc(100vh - 280px)"
              @sort-change="handleSortChange"
            >
              <el-table-column prop="documentName" label="档案名称" min-width="200" />
              <el-table-column prop="documentType" label="档案类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getArchiveTypeTag(row.documentType)">
                    {{ getArchiveTypeName(row.documentType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="documentDate" label="档案日期" width="120" sortable>
                <template #default="{ row }">
                  {{ formatDate(row.documentDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="documentPurpose" label="档案用途" width="150">
                <template #default="{ row }">
                  {{ row.documentPurpose || '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="documentSource" label="档案来源" width="150">
                <template #default="{ row }">
                  {{ row.documentSource || '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" width="200">
                <template #default="{ row }">
                  <el-tooltip v-if="row.remark" :content="row.remark" placement="top">
                    <span>{{ row.remark }}</span>
                  </el-tooltip>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                    {{ row.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="attachmentCount" label="附件" width="100">
                <template #default="{ row }">
                  <el-button 
                    type="info" 
                    size="small" 
                    @click="handleViewAttachments(row)"
                    :disabled="!row.attachmentIds || row.attachmentIds.length === 0"
                  >
                    <el-icon><Document /></el-icon>
                    {{ getAttachmentCount(row.attachmentIds) }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <div class="action-buttons">

                    <el-button type="warning" size="small" @click="handleEdit(row)">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="handleDelete(row)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-wrapper">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="totalCount"
                layout="total, sizes, prev, pager, next, jumper"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 附件对话框 -->
    <el-dialog
      v-model="attachmentDialogVisible"
      title="档案附件"
      width="800px"
      class="attachment-dialog"
    >
      <div class="attachment-content">
        <div class="archive-info">
          <h4>{{ selectedArchive?.documentName }}</h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">档案名称:</span>
              <span class="value">{{ selectedArchive?.documentName }}</span>
            </div>
            <div class="info-item">
              <span class="label">档案类型:</span>
              <span class="value">{{ getArchiveTypeName(selectedArchive?.documentType) }}</span>
            </div>
            <div class="info-item">
              <span class="label">档案日期:</span>
              <span class="value">{{ formatDate(selectedArchive?.documentDate) }}</span>
            </div>
          </div>
        </div>
        
        <div class="attachment-list" v-if="attachmentList.length > 0">
          <div 
            v-for="attachment in attachmentList" 
            :key="attachment.id" 
            class="attachment-item"
          >
            <div class="attachment-info">
              <div class="attachment-name">{{ attachment.originalFilename }}</div>
              <div class="attachment-meta">
                <span class="file-size">{{ formatFileSize(attachment.fileSize) }}</span>
                <span class="file-type">{{ attachment.fileType }}</span>
                <span class="upload-time">{{ formatAttachmentDate(attachment.createTime) }}</span>
              </div>
            </div>
            <div class="attachment-actions">
              <el-button type="primary" size="small" @click="previewAttachment(attachment)">
                <el-icon><View /></el-icon>
                预览
              </el-button>
              <el-button type="success" size="small" @click="downloadAttachment(attachment)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="no-attachments" v-else>
          <el-empty description="暂无附件" />
        </div>
      </div>
    </el-dialog>

    <!-- 新建/编辑档案对话框 -->
    <el-dialog
      v-model="archiveDialogVisible"
      :title="dialogTitle"
      width="800px"
      class="archive-dialog"
    >
      <el-form
        :model="archiveForm"
        :rules="archiveRules"
        ref="archiveFormRef"
        label-width="120px"
        class="archive-form"
      >
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <div class="form-row">
            <el-form-item label="档案名称" prop="documentName">
              <el-input
                v-model="archiveForm.documentName"
                placeholder="请输入档案名称"
                @blur="checkArchiveNumber"
              />
            </el-form-item>
            <el-form-item label="档案类型" prop="documentType">
              <el-tree-select
                v-model="archiveForm.documentType"
                :data="archiveTypeTreeData"
                :props="archiveTypeTreeProps"
                placeholder="请选择档案类型"
                style="width: 100%"
                clearable
                check-strictly
                :render-after-expand="false"
                @change="handleArchiveTypeChange"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="档案日期" prop="documentDate">
              <el-date-picker
                v-model="archiveForm.documentDate"
                type="date"
                placeholder="请选择档案日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="档案用途" prop="documentPurpose">
              <el-input
                v-model="archiveForm.documentPurpose"
                placeholder="请输入档案用途"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="档案来源" prop="documentSource">
              <el-input
                v-model="archiveForm.documentSource"
                placeholder="请输入档案来源"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="archiveForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </div>
        </div>

        <div class="form-section">
          <div class="section-title">附件上传</div>
          <el-upload
            ref="uploadRef"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="uploadData"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleFileRemove"
            multiple
            class="upload-area"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持任意格式文件，单个文件不超过50MB
              </div>
            </template>
          </el-upload>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="archiveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { 
  Search, Plus, Refresh, ArrowLeft, ArrowRight, 
  View, Edit, Delete, Document, Download, Upload,
  QuestionFilled, More
} from '@element-plus/icons-vue'
import { archiveTypeApi } from '@/api/archiveTypeApi'
import * as archiveApi from '@/api/archiveApi'
import * as attachmentApi from '@/api/attachmentApi'
import PageHeader from '@/components/layout/PageHeader.vue'

// 响应式数据
const searchKeyword = ref('')
const dateRange = ref([])
const selectedYear = ref('')
const selectedCategory = ref(null)
const sidebarCollapsed = ref(false)
const categoryLoading = ref(false)
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const totalCount = ref(0)

// 档案列表数据
const archiveList = ref([])

// 分类树数据
const categoryTreeData = ref([])
const categoryTreeRef = ref()

// 档案类型数据
const archiveTypes = ref([])
const archiveTypeTreeData = ref([])

// 对话框相关
const archiveDialogVisible = ref(false)
const attachmentDialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const archiveFormRef = ref()

// 附件相关
const attachmentList = ref([])
const selectedArchive = ref(null)

// 文件上传相关
const uploadRef = ref()
const fileList = ref([])
const uploadUrl = '/api/attachments/upload'
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}
const uploadData = {
  subDirectory: 'archive'
}

// 表单数据
const archiveForm = reactive({
  id: null,
  documentName: '',
  documentType: null,
  documentDate: '',
  documentPurpose: '',
  documentSource: '',
  remark: '',
  attachmentIds: ''
})

// 表单验证规则
const archiveRules = {
  documentName: [
    { required: true, message: '请输入档案名称', trigger: 'blur' },
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ],
  documentType: [
    { required: true, message: '请选择档案类型', trigger: 'change' }
  ],
  documentDate: [
    { required: true, message: '请选择档案日期', trigger: 'change' }
  ]
}

// 分类树配置
const categoryTreeProps = {
  children: 'children',
  label: 'typeName'
}

// 档案类型树配置
const archiveTypeTreeProps = {
  children: 'children',
  label: 'typeName',
  value: 'id'
}

// 年份选项
const yearOptions = computed(() => {
  const currentYear = new Date().getFullYear()
  const years = []
  for (let i = currentYear; i >= currentYear - 10; i--) {
    years.push(i)
  }
  return years
})

// 方法
const loadArchiveTypes = async () => {
  try {
    // 加载树状结构的档案类型数据
    const response = await archiveTypeApi.getTreeStructure()
    archiveTypeTreeData.value = response.data || []
    
    // 同时加载平铺的档案类型数据用于其他功能
    const flatResponse = await archiveTypeApi.getArchiveTypes()
    archiveTypes.value = flatResponse.data?.content || []
  } catch (error) {
    console.error('加载档案类型失败:', error)
    ElMessage.error('加载档案类型失败')
  }
}

const loadCategoryTree = async () => {
  try {
    categoryLoading.value = true
    const response = await archiveTypeApi.getTreeStructure()
    const treeData = buildTree(response.data || [])
    
    // 添加"全部"选项到树的最顶部
    categoryTreeData.value = [
      {
        id: 'all',
        typeName: '全部档案',
        typeDescription: '显示所有档案',
        children: [],
        status: 1,
        archiveCount: await getTotalArchiveCount()
      },
      ...treeData
    ]
    
    // 为每个分类添加档案数量
    await addArchiveCountsToTree(categoryTreeData.value)
  } catch (error) {
    console.error('加载分类树失败:', error)
    ElMessage.error('加载分类树失败')
  } finally {
    categoryLoading.value = false
  }
}

// 获取总档案数量
const getTotalArchiveCount = async () => {
  try {
    const response = await archiveApi.getArchives({ page: 1, size: 1 })
    return response.data?.total || 0
  } catch (error) {
    console.error('获取总档案数量失败:', error)
    return 0
  }
}

// 为树状结构添加档案数量
const addArchiveCountsToTree = async (treeData) => {
  for (const node of treeData) {
    if (node.id !== 'all') {
      try {
        const response = await archiveApi.getArchives({ 
          page: 1, 
          size: 1, 
          documentType: node.id 
        })
        node.archiveCount = response.data?.total || 0
      } catch (error) {
        console.error(`获取分类 ${node.id} 档案数量失败:`, error)
        node.archiveCount = 0
      }
    }
    
    if (node.children && node.children.length > 0) {
      await addArchiveCountsToTree(node.children)
    }
  }
}

// 构建树状结构
const buildTree = (data) => {
  const map = {}
  const result = []

  // 创建映射
  data.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  // 构建树状结构
  data.forEach(item => {
    const node = map[item.id]
    if (item.parentId === 0 || item.parentId === null || item.parentId === undefined || !map[item.parentId]) {
      result.push(node)
    } else {
      map[item.parentId].children.push(node)
    }
  })

  return result
}

const loadArchiveList = async () => {
  try {
    tableLoading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      search: searchKeyword.value,
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }
    
    // 如果有选中的分类且不是"全部"，添加文档类型过滤
    if (selectedCategory.value && selectedCategory.value.id !== 'all') {
      params.documentType = selectedCategory.value.id
    }
    
    console.log('加载档案列表参数:', params)
    const response = await archiveApi.getArchives(params)
    archiveList.value = response.data?.content || []
    totalCount.value = response.data?.total || 0
  } catch (error) {
    console.error('加载档案列表失败:', error)
    ElMessage.error('加载档案列表失败')
  } finally {
    tableLoading.value = false
  }
}

const handleCategoryClick = (data) => {
  console.log('=== 分类点击事件 ===')
  console.log('点击的分类数据:', data)
  
  selectedCategory.value = data
  
  if (data.id === 'all') {
    // 点击"全部"选项，清除分类过滤
    selectedCategory.value = null
  }
  
  console.log('当前选中的分类:', selectedCategory.value)
  
  // 重新加载数据
  currentPage.value = 1
  loadArchiveList()
  
  console.log('=== 分类点击事件结束 ===')
}

const handleCategoryExpand = async (data) => {
  if (!data.children || data.children.length === 0) {
    try {
      const response = await archiveTypeApi.getChildrenByParentId(data.id)
      data.children = response.data || []
    } catch (error) {
      console.error('加载子分类失败:', error)
    }
  }
}

const handleCategoryCollapse = (data) => {
  // 可以在这里添加折叠逻辑
}

const refreshCategories = () => {
  loadCategoryTree()
}

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

const handleSearch = () => {
  currentPage.value = 1
  loadArchiveList()
}

const handleDateRangeChange = () => {
  handleSearch()
}

const handleYearChange = () => {
  handleSearch()
}

const handleReset = () => {
  searchKeyword.value = ''
  dateRange.value = []
  selectedYear.value = ''
  selectedCategory.value = null
  currentPage.value = 1
  loadArchiveList()
}

// 更多操作处理
const handleMoreAction = (command) => {
  switch (command) {
    case 'reset':
      handleReset()
      break
    default:
      break
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadArchiveList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadArchiveList()
}

const handleSortChange = (column) => {
  // 处理排序
  loadArchiveList()
}

const isLeafCategory = (category) => {
  return !category || !category.children || category.children.length === 0
}

const handleAdd = () => {
  dialogTitle.value = '新建档案'
  resetArchiveForm()
  archiveDialogVisible.value = true
}

const handleView = (row) => {
  // 查看档案详情
  console.log('查看档案:', row)
}

const handleEdit = async (row) => {
  dialogTitle.value = '编辑档案'
  Object.assign(archiveForm, row)
  
  // 加载附件信息
  if (row.attachmentIds) {
    try {
      const attachmentIds = row.attachmentIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
      if (attachmentIds.length > 0) {
        const response = await attachmentApi.getAttachmentsBatch(attachmentIds)
        // 转换为el-upload组件需要的格式
        fileList.value = (response.data || []).map(attachment => ({
          uid: attachment.id,
          name: attachment.originalFilename,
          status: 'success',
          url: `/api/attachments/${attachment.id}/download`,
          response: {
            id: attachment.id,
            originalFilename: attachment.originalFilename,
            fileSize: attachment.fileSize,
            fileType: attachment.fileType
          }
        }))
      } else {
        fileList.value = []
      }
    } catch (error) {
      console.error('加载附件失败:', error)
      fileList.value = []
    }
  } else {
    fileList.value = []
  }
  
  archiveDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个档案吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await archiveApi.deleteArchive(row.id)
    ElMessage.success('删除成功')
    loadArchiveList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除档案失败:', error)
      ElMessage.error('删除档案失败')
    }
  }
}

const handleViewAttachments = async (row) => {
  try {
    selectedArchive.value = row
    attachmentDialogVisible.value = true
    
    if (row.attachmentIds) {
      const attachmentIds = row.attachmentIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
      if (attachmentIds.length > 0) {
        const response = await attachmentApi.getAttachmentsBatch(attachmentIds)
        attachmentList.value = response.data || []
      } else {
        attachmentList.value = []
      }
    } else {
      attachmentList.value = []
    }
  } catch (error) {
    console.error('获取附件失败:', error)
    attachmentList.value = []
    ElMessage.error('获取附件失败')
    // 如果获取附件失败，关闭对话框
    attachmentDialogVisible.value = false
  }
}

const previewAttachment = async (attachment) => {
  // 参数验证
  if (!attachment || !attachment.id) {
    ElMessage.error('附件信息无效')
    return
  }
  
  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载预览...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const response = await attachmentApi.previewAttachment(attachment.id)
    
    if (!response || !response.data) {
      throw new Error('附件数据为空')
    }
    
    const blob = new Blob([response.data], { type: attachment.fileType || 'application/octet-stream' })
    const url = URL.createObjectURL(blob)
    
    // 延迟打开预览窗口，确保URL对象创建完成
    setTimeout(() => {
      try {
        const newWindow = window.open(url, '_blank')
        if (!newWindow) {
          ElMessage.warning('浏览器阻止了弹窗，请允许弹窗后重试')
        }
        // 延迟清理URL对象
        setTimeout(() => {
          try {
            URL.revokeObjectURL(url)
          } catch (e) {
            console.warn('清理URL对象失败:', e)
          }
        }, 2000)
      } catch (e) {
        console.error('打开预览窗口失败:', e)
        ElMessage.error('预览窗口打开失败')
      }
    }, 200)
    
    ElMessage.success('预览已打开')
  } catch (error) {
    console.error('预览附件失败:', error)
    ElMessage.error('预览附件失败: ' + (error.message || '未知错误'))
  } finally {
    // 确保加载状态关闭
    setTimeout(() => {
      try {
        loadingInstance.close()
      } catch (e) {
        console.warn('关闭加载状态失败:', e)
      }
    }, 200)
  }
}

const downloadAttachment = async (attachment) => {
  // 参数验证
  if (!attachment || !attachment.id) {
    ElMessage.error('附件信息无效')
    return
  }
  
  // 显示加载提示
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在准备下载...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const response = await attachmentApi.downloadAttachment(attachment.id)
    
    if (!response || !response.data) {
      throw new Error('附件数据为空')
    }
    
    const blob = new Blob([response.data], { type: attachment.fileType || 'application/octet-stream' })
    const url = URL.createObjectURL(blob)
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = url
    link.download = attachment.originalFilename || `附件_${attachment.id}`
    link.style.display = 'none'
    
    // 添加到DOM并触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 延迟清理URL对象
    setTimeout(() => {
      try {
        URL.revokeObjectURL(url)
      } catch (e) {
        console.warn('清理URL对象失败:', e)
      }
    }, 2000)
    
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载附件失败:', error)
    ElMessage.error('下载附件失败: ' + (error.message || '未知错误'))
  } finally {
    // 确保加载状态关闭
    setTimeout(() => {
      try {
        loadingInstance.close()
      } catch (e) {
        console.warn('关闭加载状态失败:', e)
      }
    }, 200)
  }
}

const checkArchiveNumber = async () => {
  if (!archiveForm.documentName) return
  
  try {
    const response = await archiveApi.checkArchiveNumber(archiveForm.documentName, archiveForm.id)
    if (!response.data) {
      ElMessage.warning('档案名称已存在')
    }
  } catch (error) {
    console.error('检查档案名称失败:', error)
  }
}

const resetArchiveForm = () => {
  Object.assign(archiveForm, {
    id: null,
    documentName: '',
    documentType: null,
    documentDate: '',
    documentPurpose: '',
    documentSource: '',
    remark: '',
    attachmentIds: ''
  })
  fileList.value = []
}

const handleUploadSuccess = (response, file, fileList) => {
  console.log('文件上传成功:', response)
  ElMessage.success('文件上传成功')
  if (!archiveForm.attachmentIds) {
    archiveForm.attachmentIds = ''
  }
  archiveForm.attachmentIds += (archiveForm.attachmentIds ? ',' : '') + response.id
}

const handleUploadError = (error, file, fileList) => {
  console.error('文件上传失败:', error)
  ElMessage.error('文件上传失败')
}

const handleFileRemove = (file, fileList) => {
  // 处理文件移除
  console.log('移除文件:', file)
}

const handleArchiveTypeChange = (value) => {
  // 处理档案类型变化
  console.log('档案类型变化:', value)
  archiveForm.documentType = value
}

const handleSubmit = async () => {
  try {
    await archiveFormRef.value.validate()
    submitLoading.value = true
    
    if (archiveForm.id) {
      await archiveApi.updateArchive(archiveForm.id, archiveForm)
      ElMessage.success('更新成功')
    } else {
      await archiveApi.createArchive(archiveForm)
      ElMessage.success('创建成功')
    }
    
    archiveDialogVisible.value = false
    loadArchiveList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 工具方法
const getArchiveTypeName = (type) => {
  const archiveType = archiveTypes.value.find(t => t.id === type)
  return archiveType ? archiveType.typeName : '未知类型'
}

const getArchiveTypeTag = (type) => {
  const archiveType = archiveTypes.value.find(t => t.id === type)
  if (!archiveType) return 'info'
  
  // 根据档案类型名称或ID来分配标签颜色
  const tagMap = {
    '合同档案': 'primary',
    '财务档案': 'success', 
    '人事档案': 'warning',
    '其他档案': 'info'
  }
  return tagMap[archiveType.typeName] || 'info'
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

const formatFileSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = size
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }
  return `${fileSize.toFixed(2)} ${units[index]}`
}

const getAttachmentCount = (attachmentIds) => {
  if (!attachmentIds) return 0
  const ids = attachmentIds.split(',').filter(id => id.trim() !== '')
  return ids.length
}



const formatAttachmentDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
  loadArchiveTypes()
  loadCategoryTree()
  loadArchiveList()
})
</script>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  overflow: hidden;
}

/* 搜索区域样式 */
.archive-search {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

.archive-date-range {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

.archive-year-select {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

.label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  white-space: nowrap;
}

.help-icon {
  color: var(--el-text-color-secondary);
  cursor: help;
}

.table-container {
  background: var(--el-bg-color);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  max-width: 100%;
  box-sizing: border-box;
  flex: 1;
  overflow: hidden;
}

.archive-layout {
  display: flex;
  height: 100%;
}

.category-sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
}

.category-sidebar.collapsed {
  width: 50px;
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.sidebar-controls {
  display: flex;
  gap: 5px;
}

.category-tree {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-name {
  font-weight: 500;
}

.node-count {
  color: #909399;
  font-size: 12px;
  font-weight: normal;
}

.status-tag {
  margin-left: auto;
}

.archive-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  margin: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.content-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.breadcrumb {
  font-size: 16px;
  font-weight: 600;
  color: var(--primary-color, #409eff);
}

.content-actions {
  display: flex;
  gap: 10px;
}

.archive-table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-height: 0;
}

.archive-table {
  width: 100%;
  height: 100%;
  flex: 1;
  min-height: 0;
}

/* 表格滚动条样式 */
.archive-table :deep(.el-table) {
  height: 100%;
}

.archive-table :deep(.el-table__body-wrapper) {
  overflow-y: auto;
  overflow-x: auto;
}

.archive-table :deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

.archive-table :deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

.archive-table :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

.archive-table :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

/* 确保表格内容可以水平滚动 */
.archive-table :deep(.el-table__body) {
  min-width: 100%;
}

.pagination-wrapper {
  padding: 15px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #e4e7ed;
  background: white;
  flex-shrink: 0;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

/* 对话框样式 */
.attachment-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.attachment-content {
  padding: 20px;
}

.archive-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.archive-info h4 {
  margin: 0 0 10px 0;
  color: var(--primary-color, #409eff);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 10px;
}

.info-item {
  display: flex;
  gap: 10px;
}

.info-item .label {
  font-weight: 600;
  color: #606266;
}

.info-item .value {
  color: #303133;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
}

.attachment-info {
  flex: 1;
}

.attachment-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.attachment-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.attachment-actions {
  display: flex;
  gap: 10px;
}

.no-attachments {
  text-align: center;
  padding: 40px;
}

/* 档案对话框样式 */
.archive-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.archive-form {
  max-height: 60vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(248, 250, 252, 0.5);
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--primary-color, #409eff);
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid var(--primary-color, #409eff);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 15px;
}

.form-row.single {
  grid-template-columns: 1fr;
}

.upload-area {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .archive-layout {
    flex-direction: column;
  }
  
  .category-sidebar {
    width: 100%;
    height: 200px;
  }
  
  .category-sidebar.collapsed {
    height: 50px;
  }
  
  .search-section {
    flex-direction: column;
    gap: 10px;
  }
  
  .search-input,
  .search-date-picker,
  .search-select {
    width: 100%;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
}
</style> 